var express = require('express');
var router = express.Router();
var multer = require('multer');
var fs = require('fs');
var path = require('path');
let { isLogin, isUser, registerUser, getGuestpieceInfo, getGuestpieceInfoCount,
  getUsercontentCount, getUsercontentInfo, getUsercontentInfoListById, getIndexlbimgList,
  getIndexZuopin, getIndexWrapper, getIndexFooter, getHomeBrand, saveUserContent } = require('../mysql/index')
const { guestpieceCount, UsercontentCount } = require('../config');
const upload = multer({ dest: 'public/uploads/' })

router.post('/islogin', async (req, res, next) => {
  let val = req.body;
  let jsonData;
  const sessionCaptcha = req.session.captcha.toLowerCase();
  // if (sessionCaptcha != val.captcha) {
  //   return res.json({
  //     flog: 0,
  //     data: '验证码不正确'
  //   });
  // }
  let data = await isLogin({
    username: val.username,
    password: val.password,
    radio: val.radio
  })
  if (!data.length) {
    jsonData = {
      code: 0,
      data: "账号或者密码错误",
      radio: val.radio
    }
  } else {
    jsonData = {
      code: 1,
      data: data,
      radio: val.radio
    }
    req.session.UserInfo = {
      username: val.username,
      radio: val.radio
    }
  }
  return res.json(jsonData)
});
router.post('/loginregister', async (req, res, next) => {
  let val = req.body;
  let jsonData = null;;
  let data = await isUser({
    username: val.username
  })
  if (data.length) {
    jsonData = {
      code: 0,
      data: '该用户名已存在'
    }
  } else {
    let info = await registerUser({
      username: val.username,
      password: val.password
    })
    if (info) {
      jsonData = {
        code: 1,
        data: data
      }
      req.session.UserInfo = {
        username: val.username,
        radio: 'user'
      }
    } else {
      jsonData = {
        code: 0,
        data: "注册失败"
      }
    }
  }
  return res.json(jsonData)
});
router.get('/guestpieceInfo/:page', async (req, res, next) => {
  let page = req.params.page;
  let count = await getGuestpieceInfoCount();
  let pageNum = Math.ceil((count / guestpieceCount));
  if (page > pageNum) {
    return res.json({
      code: 0,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * guestpieceCount;
  let data = await getGuestpieceInfo(num);
  res.json({
    code: 1,
    data,
    pageNum: count
  })
});
router.get('/usercontentInfo/:page', async (req, res, next) => {
  let page = req.params.page;
  let count = await getUsercontentCount();
  let pageNum = Math.ceil((count / UsercontentCount));
  if (page > pageNum) {
    return res.json({
      code: 0,
      data: "数据已经加载完毕"
    });
  }
  var num = (page - 1) * UsercontentCount;
  let data = await getUsercontentInfo(num);
  res.json({
    code: 1,
    data,
    pageNum: count
  })
});
router.get('/getUsercontentInfoListById/:id', async (req, res, next) => {
  let id = req.params.id;
  let data = await getUsercontentInfoListById(id);
  res.json({
    code: 1,
    data
  })
});
router.get('/getIndexlbimgList', async (req, res, next) => {
  let data = await getIndexlbimgList();
  res.json({
    code: 1,
    data
  })
});
router.get('/getIndexZuopin', async (req, res, next) => {
  let data = await getIndexZuopin();
  res.json({
    code: 1,
    data
  })
});
router.get('/getIndexWrapper', async (req, res, next) => {
  let data = await getIndexWrapper();
  res.json({
    code: 1,
    data
  })
});
router.get('/getIndexFooter', async (req, res, next) => {
  let data = await getIndexFooter();
  res.json({
    code: 1,
    data
  })
});
router.get('/getHomeBrand', async (req, res, next) => {
  let data = await getHomeBrand();
  res.json({
    code: 1,
    data
  })
});
router.post('/setUserComment', upload.single('file'), async (req, res, next) => {
  fs.readFile(req.file.path, async (err, data) => {
    if (err) { return res.send("上传错误") };
    let filename = Date.now() + req.file.originalname;
    fs.writeFile(path.join(__dirname, '../public/uploads/' + filename), data, async err => {
      if (err) { return res.send("写入错误") };
      let nowDate = new Date()
      let year = nowDate.getFullYear()
      let month = nowDate.getMonth() + 1
      let day = nowDate.getDate()
      if (month < 10) month = '0' + month
      if (day < 10) day = '0' + day
      let time = year + '-' + month + '-' + day;
      let info = {
        name: "11",
        // name:req.session.UserInfo.username
        time: time,
        icon: '/apis/uploads/' + filename,
        content: req.body.val
      }
      let data = await saveUserContent(info);
      if (data) {
        res.json({
          code: 1,
          data: "评论成功"
        })
      }
    })
  });

})


module.exports = router;
